package com.xxl.job.admin.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.dao.XxlJobInfoDao;
import com.xxl.job.admin.service.XxlJobInfoService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

import static com.xxl.job.admin.core.model.table.Tables.XXL_JOB_INFO;

@Service
public class XxlJobInfoServiceImpl extends ServiceImpl<XxlJobInfoDao, XxlJobInfo> implements XxlJobInfoService {
    @Override
    public List<XxlJobInfo> getJobsByGroup(int jobGroup) {
        return list(XXL_JOB_INFO.JOB_GROUP.eq(jobGroup));
    }
    @Override
    public List<XxlJobInfo> scheduleJobQuery(long l, int preReadCount) {
        QueryWrapper query=QueryWrapper.create()
                .select()
                .from(XXL_JOB_INFO)
                .where(XXL_JOB_INFO.TRIGGER_STATUS.eq(1))
                .and(XXL_JOB_INFO.TRIGGER_NEXT_TIME.le(l))
                .orderBy(XXL_JOB_INFO.ID.asc())
                .limit(preReadCount);
        return list(query);
    }

    @Override
    public int scheduleUpdate(XxlJobInfo jobInfo) {
        XxlJobInfo xxlJobInfo= new XxlJobInfo();
        xxlJobInfo.setTriggerStatus(jobInfo.getTriggerStatus());
        xxlJobInfo.setTriggerLastTime(jobInfo.getTriggerLastTime());
        xxlJobInfo.setTriggerNextTime(jobInfo.getTriggerNextTime());
        xxlJobInfo.setId(jobInfo.getId());
     boolean i = updateById(jobInfo);
     return i?1:0;
    }

    @Override
    public Page<XxlJobInfo> pageList(int start, int length, int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author) {

        QueryWrapper query=QueryWrapper.create()
                .select()
                .from(XXL_JOB_INFO)
                .where(XXL_JOB_INFO.JOB_GROUP.eq(jobGroup).when(jobGroup>0))
                .and(XXL_JOB_INFO.TRIGGER_STATUS.eq(triggerStatus).when(triggerStatus>=0))
                .and(XXL_JOB_INFO.JOB_DESC.like(jobDesc).when(StringUtils.hasText(jobDesc)))
                .and(XXL_JOB_INFO.EXECUTOR_HANDLER.like(executorHandler).when(StringUtils.hasText(executorHandler)))
                .and(XXL_JOB_INFO.AUTHOR.like(author).when(StringUtils.hasText(author)))
                .orderBy(XXL_JOB_INFO.ID.desc());
        Page<XxlJobInfo> xxlJobInfoPage = mapper.paginate(start,length,query);
        return xxlJobInfoPage;
    }
}
